package cn.hiapi.user.api;

import cn.hiapi.basic.ResponseEntity;
import cn.hiapi.basic.controller.BasicController;
import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.PageRequest;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.redis.data.LockConst;
import cn.hiapi.basic.security.TokenGet;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.ILockService;
import cn.hiapi.interfaces.user.IUserService;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.*;
import cn.hiapi.shopkeeper.entity.order.*;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.enums.OrderStatus;
import cn.hiapi.shopkeeper.service.Shopkeeper;
import cn.hiapi.shopkeeper.service.activity.*;
import cn.hiapi.shopkeeper.service.order.*;
import cn.hiapi.user.api.request.VoteRequest;
import cn.hiapi.user.dto.BasicUser;
import cn.hiapi.user.request.GiftOrderRequest;
import cn.hiapi.utils.DateUtils;
import cn.hiapi.utils.JsonUtils;
import cn.hiapi.utils.RandomUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2022/12/31 20:58
 */
@RestController
@RequestMapping("/user/activity")
public class UserActivityController extends BasicController {

    private final DispatchContext dispatchContext;


    public UserActivityController(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }


    @ApiOperation(value = "我的抽奖次数", notes = "我的抽奖次数", nickname = "AdinZ")
    @GetMapping("/lottery-count")
    public ResponseEntity lotteryCount(@RequestParam("aid") long aid) {
        Token<Object> token = TokenGet.get();

        String lock = LockConst.getLock("lottery-count", aid + "_" + token.getFid());
        try {
            boolean b = this.dispatchContext.getServiceOne(ILockService.class).lock(lock);
            if (b) {
                long newGift = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).count(new QueryWrapper()
                        .eq("inviteUid", token.getFid())
                        .eq("uid", 0)
                        .eq("aid", aid).eq("newGift", 1));
                if (newGift == 0) {
                    ActivityInviteRecord record = new ActivityInviteRecord();
                    record.setType(ActivityType.LOTTERY);
                    record.setInviteUid(token.getFid());
                    record.setAid(aid);
                    record.setNewGift(1);
                    record.setUid(0);
                    record.setRemark("新客初次进入抽奖活动赠送一次");
                    this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).save(record);
                }
            }
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }
        Object count = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).lotteryCount(token.getFid(), aid);
        return toSuccess("请求成功", count);
    }


    @ApiOperation(value = "立即抽奖", notes = "立即抽奖", nickname = "AdinZ")
    @GetMapping("/lottery")
    public ResponseEntity lottery(@RequestParam("aid") long aid) {
        Token<Object> token = TokenGet.get();
        String lock = LockConst.getLock("lottery", token.getFid());
        try {
            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);
            Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(aid);
            if (activity == null) return toError("活动不存在");
            activity.verifyStatusThr();
            if (activity.getType() != ActivityType.LOTTERY) return toError("活动类型错误");
            //抽奖活动
            ActivityLottery lottery = this.dispatchContext.getServiceOne(ActivityLotteryService.class).getByAid(activity.getId());
            if (lottery == null) return toError("抽奖活动不存在");

            //抽奖次数
            List<ActivityInviteRecord> lotteryCount = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).lotteryList(token.getFid(), aid);
            if (lotteryCount.size() < 1) return toError("没有抽奖次数了");


            long startTime = DateUtils.todayStart(0).getTime();
            long endTime = DateUtils.todayEnd(0).getTime();
            //总抽奖次数
            long totalCount = this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class)
                    .count(new QueryWrapper().eq("buyerId", token.getFid())
                            .eq("aid", activity.getId())
                            .between("updated", startTime, endTime).eq("status", 1));

            if (totalCount >= lottery.getDayCount()) {
                return toError("超出今日抽奖,明天再来吧");
            }

            //中奖次数
            long lotteryTotalCount = this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class)
                    .count(new QueryWrapper().eq("buyerId", token.getFid()).between("updated", startTime, endTime)
                            .eq("aid", activity.getId())
                            .eq("status", 1).eq("lotteryState", 1));

            //抽奖入口概率
            boolean lotteryStatus = Shopkeeper.lottery(lottery.getRate(), 0);

            ActivityLotteryOrder order = new ActivityLotteryOrder();
            order.setStatus(1);
            order.setShopId(activity.getShopId());
            order.setBuyerId(token.getFid());
            order.setAid(activity.getId());

            ActivityInviteRecord record = lotteryCount.get(0);
            record.setStatus(1);
            this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).save(record);

            if (!lotteryStatus || lotteryTotalCount >= lottery.getDayLottery()) {
                this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class).save(order);
                return toResult(202, "奖品与您擦肩而过");
            }
            List<ActivityLotteryItem> items = this.dispatchContext.getServiceOne(ActivityLotteryItemService.class).findByAid(activity.getId());
            List<ActivityLotteryItem> collect = items.stream().filter(e -> {
                long count = this.dispatchContext.getServiceOne(ProductNumService.class).total(e.getAid(), String.valueOf(e.getItemId()), AppConst.ACTIVITY_SELL_TOTAL);
                return e.getStockNum() > count;
            }).collect(Collectors.toList());
            AtomicBoolean updateStatus = new AtomicBoolean(false);
            collect.forEach(e -> {
                if (e.getItemId() == 0) {
                    updateStatus.set(true);
                    e.setItemId(RandomUtils.randomSnowflake());
                }
            });
            Map<Long, BigDecimal> map = new ConcurrentHashMap<>();
            for (ActivityLotteryItem e : collect) {
                map.put(e.getItemId(), e.getRate());
            }
            if (map.isEmpty()) throw new BasicException("奖品已经没了");
            long lotteryId = Shopkeeper.lottery(map);


            if (updateStatus.get()) {
                this.dispatchContext.getServiceOne(ActivityLotteryItemService.class).save(collect);
            }


            Optional<ActivityLotteryItem> optional = collect.stream().filter(e -> e.getItemId() == lotteryId).findFirst();
            ActivityOrder activityOrder = null;
            if (optional.isPresent()) {
                ActivityLotteryItem item = optional.get();
                order.setLotteryState(1);
                order.setTitle(item.getTitle());
                order.setThumb(item.getThumb());
                order.setPrice(item.getPrice());
                //加一个销量
                this.dispatchContext.getServiceOne(ProductNumService.class).addNumber(activity.getId(), String.valueOf(item.getItemId()), AppConst.ACTIVITY_SELL_TOTAL, 1);
                //创建我的服务
                activityOrder = new ActivityOrder();
                activityOrder.setShopId(activity.getShopId());
                activityOrder.setBuyerId(token.getFid());
                activityOrder.setAid(activity.getId());
                activityOrder.setTitle(item.getTitle());
                activityOrder.setThumb(item.getThumb());
                activityOrder.setActivityType(activity.getType());
                activityOrder.setPrice(item.getPrice());
                activityOrder.setCostPrice(activity.getPrice());
                activityOrder.setStatusType(0);
                activityOrder.setStatus(OrderStatus.WAIT_USE);
                activityOrder.setFidType(AppConst.ACTIVITY_LOTTERY);
                activityOrder.setUseStart(activity.getUseStart());
                activityOrder.setUseEnd(activity.getUseEnd());
            }
            this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class).save(order);
            if (activityOrder != null) {
                activityOrder.setFid(order.getId());
                this.dispatchContext.getServiceOne(ActivityOrderService.class).save(activityOrder);
                order.setOid(activityOrder.getId());
                this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class).save(order);
                //抽奖活动添加核销码
                this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).createCode(activityOrder);
                return toSuccess("恭喜你中奖了", JsonUtils.builder()
                        .put("serviceId", activityOrder.getId())
                        .put("title", activityOrder.getTitle())
                        .put("thumb", activityOrder.getThumb())
                        .put("price", activityOrder.getPrice())
                        .put("itemId", optional.get().getItemId())
                        .build());
            }
            return toResult(202, "奖品与您擦肩而过");
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }
    }


    @ApiOperation(value = "我的中奖记录", notes = "我的中奖记录", nickname = "AdinZ")
    @GetMapping("/lottery-record")
    public ResponseEntity lotteryRecord(@RequestParam("aid") long aid) {
        Token<Object> token = TokenGet.get();


        QueryWrapper wrapper = new QueryWrapper().eq("lotteryState", 1);
        wrapper.eq("aid", aid).eq("buyerId", token.getFid());
        List<ActivityLotteryOrder> response = this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class)
                .findList(wrapper, Sort.by(Sort.Direction.DESC, "id"));
        List<JSONObject> collect = response.stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getBuyerId());
            return JsonUtils.builder()
                    .put("user", base)
                    .put("title", e.getTitle())
                    .put("thumb", e.getThumb())
                    .put("price", e.getPrice())
                    .put("oid", e.getOid())
                    .put("aid", e.getAid())
                    .put("created", e.getCreated())
                    .build();
        }).collect(Collectors.toList());
        return toSuccess(collect);
    }

    @ApiOperation(value = "领取砍价", notes = "领取砍价", nickname = "AdinZ")
    @GetMapping("/bargain")
    @Transactional
    public ResponseEntity bargainGet(@RequestParam("aid") long aid) {
        Token<Object> token = TokenGet.get();
        Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(aid);
        if (activity == null) return toError("活动不存在");
        String verifyStatus = activity.verifyStatus();
        if (StringUtils.isNotEmpty(verifyStatus)) return toError(verifyStatus);
        if (activity.getStartTime() > System.currentTimeMillis()) return toError("活动还没开始");

        if (activity.getEndTime() < System.currentTimeMillis()) return toError("活动已结束");

        ActivityBargain entity = (ActivityBargain) this.dispatchContext.getServiceOne(ActivityFactory.class).get(activity.getType()).getByAid(activity.getId());
        if (entity == null) return toError("砍价活动错误");

        if (entity.getLimitNum() != null && entity.getLimitNum() > 0) {
            long count = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(
                    new QueryWrapper().eq("aid", activity.getId())
                            .eq("buyerId", token.getFid())
                            .eq("statusType", 1).eq("activityType", activity.getType())
            );
            if (count >= entity.getLimitNum())
                throw new BasicException("超过限购数量");
        }

        ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(aid, token.getFid());
        if (order == null) {
            order = new ActivityBargainOrder();
            order.setAid(aid);
            order.setBuyerId(token.getFid());
            order.setShopId(activity.getShopId());
            order.setMinPrice(entity.getMinPrice());
            order.setCutCount(entity.getCutCount());
            this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).save(order);
        }
        JSONObject data = JsonUtils.builder().build();
        data.put("bid", order.getId());//我的砍价活动id
        return toSuccess(data);
    }


    @ApiOperation(value = "砍价状态", notes = "砍价状态", nickname = "AdinZ")
    @GetMapping("/bargain-status")
    public ResponseEntity bargainExists(@RequestParam("aid") long aid) {
        Token<Object> token = TokenGet.get();
        ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(aid, token.getFid());
        if (order == null) return toError("还没参与活动");
        JSONObject data = JsonUtils.builder().build();
        data.put("bid", order.getId());//我的砍价活动id
        return toSuccess(data);
    }


    @ApiOperation(value = "我的砍价记录", notes = "我的砍价记录", nickname = "AdinZ")
    @GetMapping("/bargain-record")
    public ResponseEntity<List> groupList(@RequestParam("aid") long aid,
                                          @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                          @RequestParam(value = "size", required = false, defaultValue = "20") int size) {
        Token<Object> token = TokenGet.get();
        ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(aid, token.getFid());
        if (order == null) return toError("没有领取砍价活动");
        ResponseEntity<List<ActivityBargainRecord>> response = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).findPage(new QueryWrapper().eq("aid", aid).eq("oid", order.getId()),
                PageRequest.of(page, size, Sort.Direction.DESC, "id"));
        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getUid());
            return JsonUtils.builder()
                    .put("user", base)
                    .put("price", e.getPrice())//砍价金额
                    .put("created", e.getCreated())//砍价时间
                    .build();
        }).collect(Collectors.toList());
        return toSuccess(collect, response.getTotal(), response.getTotalPage());
    }


    @ApiOperation(value = "帮好友砍价", notes = "帮好友砍价", nickname = "AdinZ")
    @GetMapping("/bargain-cut")
    @Transactional
    public ResponseEntity bargainCut(@RequestParam("bid") long bid) {
        Token<Object> token = TokenGet.get();
        String lock = LockConst.getLock("bargain-cut", token.getFid());
        try {
            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);
            boolean exists = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).exists(bid, token.getFid());
            if (exists) return toError("您已经助力砍价过了");

            ActivityBargainOrder order = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(bid);
            if (order == null) return toError("助力砍价单不存在");
            if (order.getStatus() != 0) return toError("砍价已结束");

            Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(order.getAid());
            if (activity == null) return toError("活动不存在");
            if (activity.getStatus() != 1) return toError("活动没开始或已结束");
            ActivityBargainRecordService.Total total = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).total(bid);
            if (total.getCount() >= order.getCutCount()) {
                return toError("已经砍完");
            }
            //砍价金额
            BigDecimal price = Shopkeeper.activityBargain(activity.getPrice().subtract(order.getMinPrice()), total.getTotalPrice(), order.getCutCount(), total.getCount());

            ActivityBargainRecord record = new ActivityBargainRecord();
            record.setOid(bid);
            record.setAid(order.getAid());
            record.setUid(token.getFid());
            record.setShopId(order.getShopId());
            record.setPrice(price);
            this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).save(record);

            JSONObject object = JsonUtils.builder()
                    .put("amount", price)//砍掉的金额
                    .put("bid", bid)//砍价单id
                    .put("aid", order.getAid())//活动id
                    .build();
            return toSuccess(object);
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }
    }

    @ApiOperation(value = "用户邀请记录", notes = "用户邀请记录", nickname = "AdinZ")
    @GetMapping("/invite-record")
    public ResponseEntity inviteRecord(@RequestParam("aid") long aid, @RequestParam(value = "page", required = false, defaultValue = "1") int page) {
        Token<Object> token = TokenGet.get();

        ResponseEntity<List<ActivityInviteRecord>> response = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).findPage(new QueryWrapper()
                .eq("inviteUid", token.getFid()).eq("aid", aid).eq("shareAward", 1), PageRequest.of(page, 20, Sort.Direction.DESC, "id")
        );

        List<JSONObject> collect = response.getData().stream().map(e -> {
            Object user = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getUid());
            return JsonUtils.builder()
                    .put("amount", e.getShareAmount())
                    .put("created", e.getCreated())
                    .put("user", user)
                    .build();
        }).collect(Collectors.toList());

        BigDecimal shareAmount = this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).totalShareAmount(token.getFid(), aid);
        ResponseEntity<List<JSONObject>> responseEntity = toSuccess(collect, response.getTotal(), response.getTotalPage());
        responseEntity.setOther(shareAmount);
        return responseEntity;
    }

    @ApiOperation(value = "投票", notes = "投票", nickname = "AdinZ")
    @PostMapping("/vote")
    public ResponseEntity activityVote(@RequestBody VoteRequest request) {
        Token<Object> token = TokenGet.get();
        String lock = LockConst.getLock("activity-vote", token.getFid());
        try {
            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);

            Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(request.getAid());
            if (activity.getType() != ActivityType.VOTE) return toError("活动类型错误");
            activity.verifyStatusThr();

            ActivityVote vote = this.dispatchContext.getServiceOne(ActivityVoteService.class).getByAid(activity.getId());
            if (vote == null) return toError("活动不存在1");
            List<ActivityVoteOther> others = this.dispatchContext.getServiceOne(ActivityVoteOtherService.class).findByAid(activity.getId());
            if (others.isEmpty()) return toError("没有投票选项");
            Optional<ActivityVoteOther> otherOptional = others.stream().filter(e -> e.getOtherId() == request.getOtherId()).findFirst();

            if (!otherOptional.isPresent()) return toError("没有的选项");


            long count = this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).count(new QueryWrapper().eq("aid", activity.getId())
                    .eq("uid", token.getFid())
            );
            if (count > 0) {
                return toError("您已经投票过了");
            }

            ActivityVoteOrder order = new ActivityVoteOrder();
            order.setAid(activity.getId());
            order.setShopId(activity.getShopId());
            order.setUid(token.getFid());
            order.setAward(vote.getAward());
            order.setOtherId(request.getOtherId());
            order.setOtherText(JSON.toJSONString(otherOptional.get()));
            if (vote.getAward() == 1) {
                List<ActivityVoteItem> items = this.dispatchContext.getServiceOne(ActivityVoteItemService.class).findByAid(activity.getId());

                Optional<ActivityVoteItem> optional = items.stream().filter(e -> e.getOtherId() == request.getOtherId()).findFirst();
                if (optional.isPresent()) {
                    ActivityVoteItem item = optional.get();
                    order.setTitle(item.getTitle());
                    order.setThumb(item.getThumb());
                    order.setBody(item.getBody());
                } else order.setAward(0);

            }
            this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).save(order);

            this.dispatchContext.getServiceOne(ProductNumService.class).addNumber(activity.getId(), AppConst.ACTIVITY_SELL_TOTAL, 1);

            JSONObject data = JsonUtils.builder().build();
            data.put("oid", order.getId());
            data.put("award", order.getAward());
            data.put("title", order.getTitle());
            data.put("thumb", order.getThumb());
            data.put("body", order.getBody());
            data.put("aid", order.getAid());


            return toSuccess(data);
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }
    }

    @ApiOperation(value = "领取奖励", notes = "领取奖励", nickname = "AdinZ")
    @GetMapping("/vote-award")
    public ResponseEntity activityVoteAward(@RequestParam("oid") long oid) {
        Token<Object> token = TokenGet.get();

        String lock = LockConst.getLock("activity-vote-award", token.getFid());
        try {

            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);

            ActivityVoteOrder order = this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).get(oid);
            if (order == null || order.getUid() != token.getFid()) return toError("奖励不存在");
            if (order.getStatus() != 0) return toError("奖励已经领取");
            Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(order.getAid());
            if (activity == null || activity.getStatus() != 1) return toError("活动不存在");
            order.setStatus(1);
            order.setUpdated(System.currentTimeMillis());
            this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).save(order);

            ActivityOrder activityOrder = new ActivityOrder();
            activityOrder.setShopId(order.getShopId());
            activityOrder.setBuyerId(token.getFid());
            activityOrder.setAid(order.getAid());
            activityOrder.setTitle(order.getTitle());
            activityOrder.setThumb(order.getThumb());
            activityOrder.setActivityType(ActivityType.VOTE);
            activityOrder.setStatusType(0);
            activityOrder.setStatus(OrderStatus.WAIT_USE);
            activityOrder.setFidType(ActivityType.VOTE.name());
            activityOrder.setFid(order.getId());
            activityOrder.setUseStart(activity.getUseStart());
            activityOrder.setUseEnd(activity.getUseEnd());
            this.dispatchContext.getServiceOne(ActivityOrderService.class).save(activityOrder);
            this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).createCode(activityOrder);
            return toSuccess(JsonUtils.builder().put("oid", activityOrder.getId()).put("created", activityOrder.getCreated()).build());
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }
    }

    @ApiOperation(value = "投票单转好友", notes = "投票单转好友", nickname = "AdinZ")
    @PostMapping("/vote-gift")
    public ResponseEntity activityVoteGift(@RequestBody GiftOrderRequest request) {

        Token<Object> token = TokenGet.get();

        String lock = LockConst.getLock("activity-vote-gift", token.getFid());
        try {

            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);

            ActivityVoteOrder order = this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).get(request.getId());
            if (order == null || order.getUid() != token.getFid()) return toError("奖励不存在");
            if (order.getStatus() != 0) return toError("奖励已经领取");
            Activity activity = this.dispatchContext.getServiceOne(ActivityService.class).get(order.getAid());
            if (activity == null || activity.getStatus() != 1) return toError("活动不存在");

            Long uid = this.dispatchContext.getServiceOne(IUserService.class).getUid(token.getMerchantId(), request.getMobile());
            if (uid == null) return toError("好友不存在");
            order.setStatus(2);
            order.setUpdated(System.currentTimeMillis());
            this.dispatchContext.getServiceOne(ActivityVoteOrderService.class).save(order);
            ActivityOrder activityOrder = new ActivityOrder();
            activityOrder.setShopId(order.getShopId());
            activityOrder.setBuyerId(uid);
            activityOrder.setAid(order.getAid());
            activityOrder.setTitle(order.getTitle());
            activityOrder.setThumb(order.getThumb());
            activityOrder.setActivityType(ActivityType.VOTE);
            activityOrder.setStatusType(0);
            activityOrder.setStatus(OrderStatus.WAIT_USE);
            activityOrder.setFidType(ActivityType.VOTE.name());
            activityOrder.setFid(order.getId());
            activityOrder.setUseStart(activity.getUseStart());
            activityOrder.setUseEnd(activity.getUseEnd());
            activityOrder.setGiftDirection(2);
            activityOrder.setGiftUid(token.getFid());
            this.dispatchContext.getServiceOne(ActivityOrderService.class).save(activityOrder);
            this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).createCode(activityOrder);
            return toSuccess();
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }


    }


}

